package cn.acyou.actions.serialVersion;

import cn.acyou.settings.MyToolsConfig;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiJavaFile;

import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 生成序列化版本号操作
 *
 * @author youfang
 * @date 2021/04/01
 */
public class GenerateSerialVersionUidAction extends AnAction {

    private static final Pattern SERIALIZABLE_PATTERN = Pattern.compile("implements.+Serializable.*\\{");

    @Override
    public void update(AnActionEvent e) {
        DataContext dataContext = e.getDataContext();
        Editor editor = CommonDataKeys.EDITOR.getData(dataContext);
        PsiFile psiFile = CommonDataKeys.PSI_FILE.getData(dataContext);
        boolean enableIt = false;
        if (psiFile instanceof PsiJavaFile && editor != null) {
            String documentText = editor.getDocument().getText();
            Matcher matcher = SERIALIZABLE_PATTERN.matcher(documentText);
            if (matcher.find()) {
                int serialVersionUidIdx = documentText.indexOf("private static final long serialVersionUID");
                if (serialVersionUidIdx < 0) {
                    enableIt = true;
                }
            }
        }
        e.getPresentation().setEnabledAndVisible(enableIt);
    }

    @Override
    public void actionPerformed(AnActionEvent e) {
        Project project = e.getProject();
        DataContext dataContext = e.getDataContext();
        Editor editor = CommonDataKeys.EDITOR.getData(dataContext);
        if (editor != null){
            String serialVersionUID = "1";
            if (MyToolsConfig.getInstance().isUseSerialVersionIdRandom()) {
                serialVersionUID = String.valueOf(new Random().nextLong());
            }
            final String text = "\n    private static final long serialVersionUID = "+serialVersionUID+"L;\n";
            Document document = editor.getDocument();
            String documentText = document.getText();
            int serialVersionUidIdx = documentText.lastIndexOf("Serializable");
            int lineNumber = editor.getDocument().getLineNumber(serialVersionUidIdx);
            int nextLineStartOffset = document.getLineStartOffset(lineNumber + 1);
            WriteCommandAction.runWriteCommandAction(project, () ->
                    document.insertString(nextLineStartOffset, text));
        }
    }
}
